package org.act.xservices.rt.xcontainer.transport.http.codec;

import org.apache.asyncweb.server.HttpServiceContext;
import org.apache.asyncweb.server.HttpServiceFilter;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;

public class HttpServiceFilterAdapter extends IoFilterAdapter
{
    private final HttpServiceFilter filter;

    public HttpServiceFilterAdapter( HttpServiceFilter filter )
    {
        this.filter = filter;
    }

    @Override
    public void messageReceived( final NextFilter nextFilter,
                                 final IoSession session, final Object message ) throws Exception
    {
        HttpServiceFilter.NextFilter nextFilterAdapter = new HttpServiceFilter.NextFilter()
        {
            public void invoke()
            {
                nextFilter.messageReceived(session, message);
            }
        };
        filter.handleRequest( nextFilterAdapter, ( HttpServiceContext ) message );
    }

    @Override
    public void filterWrite( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest )
            throws Exception
    {
        HttpServiceFilter.NextFilter nextFilterAdapter = new HttpServiceFilter.NextFilter()
        {
            public void invoke()
            {
                nextFilter.filterWrite( session, writeRequest );
            }
        };

        HttpServiceContext context = ( HttpServiceContext ) writeRequest.getMessage();
        filter.handleResponse( nextFilterAdapter, context );
    }
}

